package com.taotao.tools.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.taotao.tools.jackson.annotations.MoneyFormat;
import com.taotao.tools.core.str.MoneyUtil;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.math.BigDecimal;


@NoArgsConstructor
public class MoneyFormatSerializer extends JsonSerializer<Object> implements ContextualSerializer {



    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException {
        if (null == value) {
            jgen.writeObject(value);
        }

        if(value instanceof BigDecimal){
            jgen.writeObject(MoneyUtil.formatMoney((BigDecimal) value));
        }else if(value instanceof Long){
            jgen.writeObject(MoneyUtil.formatMoney(new BigDecimal(value.toString())));
        }else if(value instanceof Integer){
            jgen.writeObject(MoneyUtil.formatMoney(new BigDecimal(value.toString())));
        }else{
            throw new RuntimeException("MoneyFormat cannot support type "+value.getClass());
        }


    }


    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty == null) {
            //为空直接跳过
            return serializerProvider.findNullValueSerializer(beanProperty);
        }

        MoneyFormat anno = beanProperty.getAnnotation(MoneyFormat.class);
        if (null == anno) {
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }

        return new MoneyFormatSerializer();
    }
}